package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ReidsConstants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.Dto.JiajiaMallOrderDto;
import com.ruoyi.system.domain.vo.JiajiaMallOrderVo;
import com.ruoyi.system.mapper.JiajiaMailOrderDetailMapper;
import com.ruoyi.system.mapper.JiajiaMallOrderMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商城订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-05
 */
@Service
public class JiajiaMallOrderServiceImpl implements IJiajiaMallOrderService
{
    private static final Logger logger = LoggerFactory.getLogger(JiajiaMallOrderServiceImpl.class);

    @Autowired
    private JiajiaMallOrderMapper jiajiaMallOrderMapper;

    @Autowired
    private JiajiaMailOrderDetailMapper jiajiaMailOrderDetailMapper;


    @Autowired
    private IJiajiaPointsFlowService iJiajiaPointsFlowService;

    @Autowired
    private IJiajiaPointsPriorityQueueService iJiajiaPointsPriorityQueueService;

    @Autowired
    private IJiajiaPointsFlowDetailService iJiajiaPointsFlowDetailService;


    @Autowired
    private ApiPayService apiPayService;

    @Autowired
    private IJiajiaPointsFlowService jiajiaPointsFlowService;

    @Autowired
    private IJiajiaPointsFlowUserdService jiajiaPointsFlowUserdService;

    @Autowired
    private  JiajiaPointsFlowUserdServiceImpl jiajiaPointsFlowUserdServiceImpl;



    /**
     * 查询商城订单
     *
     * @param id 商城订单主键
     * @return 商城订单
     */
    @Override
    public JiajiaMallOrderVo selectJiajiaMallOrderById(Long id)
    {
        return jiajiaMallOrderMapper.selectJiajiaMallOrderById(id);
    }

    /**
     * 查询商城订单列表
     *
     * @param jiajiaMallOrderDto 商城订单
     * @return 商城订单
     */
    @Override
    public List<JiajiaMallOrderVo> selectJiajiaMallOrderList(JiajiaMallOrderDto jiajiaMallOrderDto)
    {
        JiajiaMallOrder jiajiaMallOrder=new JiajiaMallOrder();
        BeanUtils.copyProperties(jiajiaMallOrderDto,jiajiaMallOrder);
        List<JiajiaMallOrderVo> jiajiaMallOrderVos = jiajiaMallOrderMapper.selectJiajiaMallOrderList(jiajiaMallOrder);
        if ("0".equals(jiajiaMallOrderDto.getStatus())){
            return jiajiaMallOrderVos.stream().filter(vo ->vo.getOrderStatus().equals("0") ).collect(Collectors.toList());
        }else if("2".equals(jiajiaMallOrderDto.getStatus())){
            return jiajiaMallOrderVos.stream().filter(vo ->vo.getOrderStatus().equals("2") ||vo.getOrderStatus().equals(3) ).collect(Collectors.toList());

        }else if("4".equals(jiajiaMallOrderDto.getStatus())){
            return jiajiaMallOrderVos.stream().filter(vo ->vo.getOrderStatus().equals("4")  ).collect(Collectors.toList());

        }else if("6".equals(jiajiaMallOrderDto.getStatus())){
            return jiajiaMallOrderVos.stream().filter(vo ->vo.getOrderStatus().equals("1") || Integer.valueOf(vo.getOrderStatus())>=6 ).collect(Collectors.toList());

        }else{
            return jiajiaMallOrderVos;

        }
    }

    /**
     * 新增商城订单
     *
     * @param jiajiaMallOrderDto 商城订单
     * @return 结果
     */
    @Override
    public Map<String ,Object> insertJiajiaMallOrder(JiajiaMallOrderDto jiajiaMallOrderDto)
    {
        Map<String,Object> map=new HashMap<>();
        JiajiaMallOrder jiajiaMallOrder=new JiajiaMallOrder();
        BeanUtils.copyProperties(jiajiaMallOrderDto,jiajiaMallOrder);
        jiajiaMallOrder.setCreateTime(DateUtils.getNowDate());
        jiajiaMallOrder.setOrderStatus("0");
        jiajiaMallOrder.setDeleted(0);
        Random random = new Random();
        //查询本人可用积分
        JiajiaPointsFlowDetail jiajiaPointsFlowDetail =new JiajiaPointsFlowDetail();
        jiajiaPointsFlowDetail.setUid(TokenUtil.getUid());
        List<JiajiaPointsFlowDetail> jiajiaPointsFlowDetails = iJiajiaPointsFlowDetailService.selectJiajiaPointsFlowDetailList(jiajiaPointsFlowDetail);
        JiajiaPointsFlowUserd jiajiaPointsFlowUserd=new JiajiaPointsFlowUserd();
        jiajiaPointsFlowUserd.setUid(TokenUtil.getUid());
        List<JiajiaPointsFlowUserd> jiajiaPointsFlowUserds = jiajiaPointsFlowUserdService.selectJiajiaPointsFlowUserdList(jiajiaPointsFlowUserd);
        Map<String, BigDecimal> collect = jiajiaPointsFlowDetails.stream()
                .collect(Collectors.groupingBy(JiajiaPointsFlowDetail::getPointsType, Collectors.reducing(BigDecimal.ZERO, JiajiaPointsFlowDetail::getProductPoints, BigDecimal::add)));

        Map<String, BigDecimal> collect1 = jiajiaPointsFlowUserds.stream()
                .collect(Collectors.groupingBy(JiajiaPointsFlowUserd::getPointsType, Collectors.reducing(BigDecimal.ZERO, JiajiaPointsFlowUserd::getProductPoints, BigDecimal::add)));

        BigDecimal profit = (collect.get("1") == null?BigDecimal.ZERO:collect.get("1") ).subtract(collect1.get("1")== null?BigDecimal.ZERO:collect1.get("1"));//当前可用利润积分
        BigDecimal queue = (collect.get("2") == null?BigDecimal.ZERO:collect.get("2") ).subtract(collect1.get("2")== null?BigDecimal.ZERO:collect1.get("2"));//当前可用排队积分
        BigDecimal free = (collect.get("0") == null?BigDecimal.ZERO:collect.get("0") ).subtract(collect1.get("0")== null?BigDecimal.ZERO:collect1.get("0"));//当前可用自由积分
        Object o = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.sys_mall_profit_margin);
        //可用于利润积分部分
        BigDecimal availableProfit = jiajiaMallOrder.getTotalPrice().multiply(new BigDecimal(o.toString()));
        if(availableProfit.compareTo(profit)>0){
            jiajiaMallOrder.setFreePoints(profit);
        }else{
            jiajiaMallOrder.setFreePoints(availableProfit);
        }
        //可用于排队积分和自由积分部分 应为排队积分收支平衡所以优先，
        BigDecimal remaining = jiajiaMallOrder.getTotalPrice().subtract(availableProfit);
        if(remaining.compareTo(queue)>0){
            jiajiaMallOrder.setQueuePoints(queue);
            //可用于自由积分的产品金额
            BigDecimal freePoints = remaining.subtract(queue);
            if(freePoints.compareTo(free)>0){
                jiajiaMallOrder.setFreePoints(queue);

                 }else{
                jiajiaMallOrder.setFreePoints(freePoints);

            }

        }else{
            jiajiaMallOrder.setQueuePoints(remaining);
            jiajiaMallOrder.setFreePoints(new BigDecimal(0));

        }
        //总积分消耗
        BigDecimal points=jiajiaMallOrder.getProfitPoints().add(jiajiaMallOrder.getQueuePoints()).add(jiajiaMallOrder.getFreePoints());
        if(jiajiaMallOrder.getTotalPrice().compareTo(points)>0){
            jiajiaMallOrder.setActualPrice(jiajiaMallOrder.getTotalPrice().subtract(points));
            map.put("type","1");//需要发起支付
        }else {
            jiajiaMallOrder.setActualPrice(new BigDecimal(0));
            map.put("type","0");//bu需要发起支付

        }
        String orderSn = System.currentTimeMillis()+""+(random.nextInt(8999)+1000);
        jiajiaMallOrder.setOrderNum(orderSn);
        jiajiaMallOrder.setUid(TokenUtil.getUid());
         jiajiaMallOrderMapper.insertJiajiaMallOrder(jiajiaMallOrder);
         jiajiaMallOrderDto.getJiajiaMailOrderDetailList().stream().forEach(a ->{
            a.setOrderId(jiajiaMallOrder.getId());
            a.setuId(jiajiaMallOrder.getUid());
            a.setDeleted(0);
            jiajiaMailOrderDetailMapper.insertJiajiaMailOrderDetail(a);

        });
        map.put("orderId",jiajiaMallOrder.getId().intValue());
        map.put("availablePoints",points);
        map.put("actualPrice",jiajiaMallOrder.getActualPrice());
        return map;
    }

    /**
     * 修改商城订单
     *
     * @param jiajiaMallOrderu 商城订单
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)//防止退款和完成订单冲突 此方法需要最高级别的事物隔离支持
    public int updateJiajiaMallOrder(JiajiaMallOrder jiajiaMallOrderu)
    {
        JiajiaMallOrderVo jiajiaMallOrderVo = jiajiaMallOrderMapper.selectJiajiaMallOrderById(jiajiaMallOrderu.getId());
        jiajiaMallOrderVo.setUpdateTime(DateUtils.getNowDate());
        JiajiaMallOrder jiajiaMallOrder=new JiajiaMallOrder();
        BeanUtils.copyProperties(jiajiaMallOrderVo,jiajiaMallOrder);
        //可用于分配的金额 商城利润率  平台转化率
        //商城利润率
        Object o = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.sys_mall_profit_margin);
        //积分转化率
        Object smpa = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.SYS_MALL_POINTS_RATION);
        //平台利润划分率
        BigDecimal dictValue1 = new BigDecimal(DictUtils.getDictValue(ReidsConstants.DISTRIBUTION_RATIO, ReidsConstants.SHOPPING_MALL));

        BigDecimal totalPrice = jiajiaMallOrder.getTotalPrice()
                .multiply(new BigDecimal(o.toString())).setScale(0, RoundingMode.DOWN)//商城利润
                .multiply(new BigDecimal(smpa.toString()).add(dictValue1)).setScale(0, RoundingMode.DOWN)
                .divide(new BigDecimal(smpa.toString()),RoundingMode.DOWN)
                .setScale(0,RoundingMode.DOWN);//舍去0
        //订单积分支付部分
        BigDecimal points = jiajiaMallOrder.getProfitPoints().add(jiajiaMallOrder.getQueuePoints()).add(jiajiaMallOrder.getFreePoints());

        if(jiajiaMallOrderu.getOrderStatus().equals("4")){
            int i = jiajiaMallOrderMapper.updateJiajiaMallOrder(jiajiaMallOrder);
            //确认收货后 开始消费积分队列

            if(totalPrice.compareTo(points)>0){
                List<JiajiaPointsPriorityQueue> pgResult=new ArrayList<>();
                List<JiajiaPointsFlow> pfResult=new ArrayList<>();
                List<JiajiaPointsFlowDetail> pfdResult=new ArrayList<>();
                //该订单有利润 开始消费积分队列
                BigDecimal profit = totalPrice.subtract(points);
                //优先队列 实际上积分已被消费 一次性算法 平衡收益
                JiajiaPointsPriorityQueue jiajiaPointsPriorityQueueDto = new JiajiaPointsPriorityQueue();
                jiajiaPointsPriorityQueueDto.setDeleted(0);
                List<JiajiaPointsPriorityQueue> jiajiaPointsPriorityQueues = iJiajiaPointsPriorityQueueService.selectJiajiaPointsPriorityQueueList(jiajiaPointsPriorityQueueDto);
                if(Optional.ofNullable(jiajiaPointsPriorityQueues).isPresent() && jiajiaPointsPriorityQueues.size()>0){
                    for (JiajiaPointsPriorityQueue jiajiaPointsPriorityQueue :jiajiaPointsPriorityQueues) {
                        if(profit.compareTo(jiajiaPointsPriorityQueue.getProductPoints())>0){
                            profit=profit.subtract(jiajiaPointsPriorityQueue.getProductPoints());
                            jiajiaPointsPriorityQueue.setRemark(jiajiaPointsPriorityQueue.getRemark()+";优先队列被订单"+jiajiaMallOrder.getId()+"消耗");
                            jiajiaPointsPriorityQueue.setDeleted(1);
                            pgResult.add(jiajiaPointsPriorityQueue);
                        } else {
                            JiajiaPointsPriorityQueue jiajiaPointsPriorityQueue1 = new JiajiaPointsPriorityQueue();
                            BeanUtils.copyProperties(jiajiaPointsPriorityQueue,  jiajiaPointsPriorityQueue1);
                            jiajiaPointsPriorityQueue1.setProductTotalPrice(jiajiaPointsPriorityQueue.getProductPoints().subtract(profit));
                            jiajiaPointsPriorityQueue1.setDeleted(0);
                            jiajiaPointsPriorityQueue1.setId(null);
                            jiajiaPointsPriorityQueue1.setRemark(jiajiaPointsPriorityQueue1.getRemark()+";优先队列"+jiajiaPointsPriorityQueue.getId()+"未消耗积分");
                            jiajiaPointsPriorityQueue.setDeleted(1);
                            jiajiaPointsPriorityQueue.setRemark(jiajiaPointsPriorityQueue.getRemark()+";优先队列被订单"+jiajiaMallOrder.getId()+"消耗");
                            pgResult.add(jiajiaPointsPriorityQueue);
                            pgResult.add(jiajiaPointsPriorityQueue1);
                            //商城订单利润已被分配完 结束业务逻辑
                            return i;
                      }
                    }


                    //有未被优先队列消费完的金额  增加客户粘性 按比例消耗积分
                    if(profit.compareTo(new BigDecimal(0))>0){
                        unlockPointsPortionally( profit, jiajiaMallOrder,pfResult, pfdResult);
                    }

                    pgResult.stream().forEach(a ->{
                        if(Optional.ofNullable(a.getId()).isPresent()){
                            iJiajiaPointsPriorityQueueService.updateJiajiaPointsPriorityQueue(a);
                        } else{
                            iJiajiaPointsPriorityQueueService.insertJiajiaPointsPriorityQueue(a);
                        }
                    });

                    pfResult.stream().forEach(a ->{
                        if(Optional.ofNullable(a.getId()).isPresent()){
                            iJiajiaPointsFlowService.updateJiajiaPointsFlow(a);
                        } else{
                            iJiajiaPointsFlowService.insertJiajiaPointsFlow(a);
                        }
                    });

                    pfdResult.stream().forEach(a ->{
                        if(Optional.ofNullable(a.getId()).isPresent()){
                            iJiajiaPointsFlowDetailService.updateJiajiaPointsFlowDetail(a);
                        } else{
                            iJiajiaPointsFlowDetailService.insertJiajiaPointsFlowDetail(a);
                        }
                    });
                }else {
                    unlockPointsPortionally( profit, jiajiaMallOrder, pfResult, pfdResult);
                }

            }
        }/*else if(jiajiaMallOrderu.getOrderStatus().equals("5")){
                //退款分退还已用积分和已解锁积分
                //退还已用积分
            JiajiaPointsFlowUserd jiajiaPointsFlowUserd=new JiajiaPointsFlowUserd();
            jiajiaPointsFlowUserd.setUsedOrderId(jiajiaMallOrder.getId());
            List<JiajiaPointsFlowUserd> jiajiaPointsFlowUserds = jiajiaPointsFlowUserdServiceImpl.selectJiajiaPointsFlowUserdList(jiajiaPointsFlowUserd);
            if(Optional.ofNullable(jiajiaPointsFlowUserds).isPresent() && jiajiaPointsFlowUserds.size()>0){}
            jiajiaPointsFlowUserds.stream().forEach(a ->{
                a.setDeleted(1);
                jiajiaPointsFlowUserdServiceImpl.updateJiajiaPointsFlowUserd(a);
            });
            //如果已完成订单还需返回已解锁积分
            if (jiajiaMallOrder.getOrderStatus().equals("4")){
                if(totalPrice.compareTo(points)>0) {
                    JiajiaPointsPriorityQueue jiajiaPointsPriorityQueue = new JiajiaPointsPriorityQueue();
                    jiajiaPointsPriorityQueue.setJiajiaOrderId();
                    jiajiaPointsPriorityQueue.setRemark();
                    jiajiaPointsPriorityQueue.setIntegralStatus();
                    iJiajiaPointsPriorityQueueService.insertJiajiaPointsPriorityQueue(jiajiaPointsPriorityQueue);

                }
            }


        }*/


        return 1;
    }



    @Override
    public int updateJiajiaMallOrderStatus(JiajiaMallOrderDto jiajiaMallOrderDto) {
        JiajiaMallOrderVo jiajiaMallOrderVo = jiajiaMallOrderMapper.selectJiajiaMallOrderById(jiajiaMallOrderDto.getOrderId());
        JiajiaMallOrder jiajiaMallOrder = new JiajiaMallOrder();
        BeanUtils.copyProperties(jiajiaMallOrderVo,jiajiaMallOrder);
        jiajiaMallOrder.setOrderStatus("2");
        jiajiaMallOrder.setTransactionId("bjx:"+jiajiaMallOrder.getId()+jiajiaMallOrder.getOrderNum());
        jiajiaPointsFlowUserdService.saveJiajiaPointsFlowUserds(jiajiaMallOrder);

        return   jiajiaMallOrderMapper.updateJiajiaMallOrder(jiajiaMallOrder);

    }

    /**
     * 批量删除商城订单
     *
     * @param ids 需要删除的商城订单主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaMallOrderByIds(String ids)
    {
        return jiajiaMallOrderMapper.deleteJiajiaMallOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商城订单信息
     *
     * @param id 商城订单主键
     * @return 结果
     */
    @Override
    public int deleteJiajiaMallOrderById(Long id)
    {
        return jiajiaMallOrderMapper.deleteJiajiaMallOrderById(id);
    }

    @Override
    public void review(JiajiaMallOrderDto jiajiaMallOrderDto) {
        //----------------------------------审核通过 发起退款
        refundPoints( jiajiaMallOrderDto);
        JiajiaMallOrderVo jiajiaMallOrderVo = jiajiaMallOrderMapper.selectJiajiaMallOrderById(jiajiaMallOrderDto.getId());
        JiajiaMallOrder target = new JiajiaMallOrder();
        BeanUtils.copyProperties(jiajiaMallOrderVo, target);
        target.setOrderStatus("5");
        jiajiaMallOrderMapper.updateJiajiaMallOrder(target);
        apiPayService.xiaoChengXuMallRefund(jiajiaMallOrderDto.getId().toString(),"");

    }


    /**
     * 开启异步 开启事物
     * @param jiajiaMallOrderDto
     */
    @Async
    @Transactional(isolation = Isolation.SERIALIZABLE)//防止退款和完成订单冲突 此方法需要最高级别的事物隔离支持
    public void refundPoints(JiajiaMallOrderDto jiajiaMallOrderDto){
/*        //查询被该订单消耗的商城积分
        JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
        jiajiaPointsFlowDetail.setUnlockOrderId(jiajiaMallOrderDto.getId());
        List<JiajiaPointsFlowDetail> jiajiaPointsFlowDetails = iJiajiaPointsFlowDetailService.selectJiajiaPointsFlowDetailList(jiajiaPointsFlowDetail);
        //需要处理的项目积分列表
        List<JiajiaPointsFlow>   list=new ArrayList<>();
        jiajiaPointsFlowDetails.stream().forEach(a ->{

            JiajiaPointsFlow jiajiaPointsFlow=new JiajiaPointsFlow();
            jiajiaPointsFlow.setJiajiaOrderId( a.getJiajiaOrderId());
            List<JiajiaPointsFlow> jiajiaPointsFlows = iJiajiaPointsFlowService.selectJiajiaPointsFlowList(jiajiaPointsFlow);
            list.addAll(jiajiaPointsFlows);
        });
        list.stream().forEach(a ->{
            if(a.getIntegralStatus().equals("0")){

                //还没解锁修改明细表状态
                jiajiaPointsFlowDetails.stream()
                        .filter(flowDetail -> flowDetail.getUnlockOrderId().equals(jiajiaMallOrderDto.getId()))
                        .forEach(flowDetail->{
                            iJiajiaPointsFlowDetailService.deleteJiajiaPointsFlowDetailById(flowDetail.getUnlockOrderId());
                        });
            }else if(a.getIntegralStatus().equals("1") ){
                //已解锁还未被消费
                jiajiaPointsFlowDetails.stream()
                        .filter(flowDetail -> flowDetail.getUnlockOrderId().equals(jiajiaMallOrderDto.getId()))
                        .forEach(flowDetail->{
                            iJiajiaPointsFlowDetailService.deleteJiajiaPointsFlowDetailById(flowDetail.getUnlockOrderId());
                        });
                a.setIntegralStatus("0");
                iJiajiaPointsFlowService.updateJiajiaPointsFlow(a);

            }else if( a.getIntegralStatus().equals("2")){
                //正在被消费或已消费完积分

                jiajiaPointsFlowDetails.stream()
                        .filter(flowDetail -> flowDetail.getUnlockOrderId().equals(jiajiaMallOrderDto.getId()))
                        .forEach(flowDetail->{
                            JiajiaPointsPriorityQueue jiajiaPointsPriorityQueue = new JiajiaPointsPriorityQueue();
                            BeanUtils.copyProperties(flowDetail,jiajiaPointsPriorityQueue);
                            jiajiaPointsPriorityQueue.setDeleted(0);
                            iJiajiaPointsPriorityQueueService.insertJiajiaPointsPriorityQueue(jiajiaPointsPriorityQueue);
                        });



            }
        });*/
        JiajiaMallOrderVo jiajiaMallOrderVo = jiajiaMallOrderMapper.selectJiajiaMallOrderById(jiajiaMallOrderDto.getId());
        jiajiaMallOrderVo.setUpdateTime(DateUtils.getNowDate());
        JiajiaMallOrder jiajiaMallOrder=new JiajiaMallOrder();
        BeanUtils.copyProperties(jiajiaMallOrderVo,jiajiaMallOrder);
        //可用于分配的金额 商城利润率  平台转化率
        //商城利润率
        Object o = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.sys_mall_profit_margin);
        //积分转化率
        Object smpa = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.SYS_MALL_POINTS_RATION);
        //平台利润划分率
        BigDecimal dictValue1 = new BigDecimal(DictUtils.getDictValue(ReidsConstants.DISTRIBUTION_RATIO, ReidsConstants.SHOPPING_MALL));

        BigDecimal totalPrice = jiajiaMallOrder.getTotalPrice()
                .multiply(new BigDecimal(o.toString())).setScale(0, RoundingMode.DOWN)//商城利润
                .multiply(new BigDecimal(smpa.toString()).add(dictValue1)).setScale(0, RoundingMode.DOWN)
                .divide(new BigDecimal(smpa.toString()),RoundingMode.DOWN)
                .setScale(0,RoundingMode.DOWN);//舍去0
        //订单积分支付部分
        BigDecimal points = jiajiaMallOrder.getProfitPoints().add(jiajiaMallOrder.getQueuePoints()).add(jiajiaMallOrder.getFreePoints());
        //退款分退还已用积分和已解锁积分
        //退还已用积分
        JiajiaPointsFlowUserd jiajiaPointsFlowUserd=new JiajiaPointsFlowUserd();
        jiajiaPointsFlowUserd.setUsedOrderId(jiajiaMallOrder.getId());
        List<JiajiaPointsFlowUserd> jiajiaPointsFlowUserds = jiajiaPointsFlowUserdServiceImpl.selectJiajiaPointsFlowUserdList(jiajiaPointsFlowUserd);
        if(Optional.ofNullable(jiajiaPointsFlowUserds).isPresent() && jiajiaPointsFlowUserds.size()>0){}
        jiajiaPointsFlowUserds.stream().forEach(a ->{
            a.setDeleted(1);
            jiajiaPointsFlowUserdServiceImpl.updateJiajiaPointsFlowUserd(a);
        });

        //如果已完成订单还需返回已解锁积分
        if (jiajiaMallOrder.getOrderStatus().equals("4")){
            if(totalPrice.compareTo(points)>0) {
                JiajiaPointsPriorityQueue jiajiaPointsPriorityQueue = new JiajiaPointsPriorityQueue();
                jiajiaPointsPriorityQueue.setJiajiaOrderId(jiajiaMallOrder.getId());
                jiajiaPointsPriorityQueue.setRemark("订单："+jiajiaMallOrder.getId()+"产生退款");
                jiajiaPointsPriorityQueue.setProductPoints(totalPrice.subtract(points));
                iJiajiaPointsPriorityQueueService.insertJiajiaPointsPriorityQueue(jiajiaPointsPriorityQueue);

            }
        }
    }


    /**
     * 按比例解锁积分计算
     * @param totalPrice  可解锁积分金额
     * @param jiajiaMallOrder 订单
     */
    public boolean unlockPointsPortionally(BigDecimal totalPrice,JiajiaMallOrder jiajiaMallOrder,List<JiajiaPointsFlow> pfResult,List<JiajiaPointsFlowDetail> pfdResult){
        //正在解锁
        JiajiaPointsFlow jiajiaPointsFlowDto=new JiajiaPointsFlow();
        jiajiaPointsFlowDto.setDeleted(0);
        jiajiaPointsFlowDto.setIntegralStatus("1");
        jiajiaPointsFlowDto.setPointsType("2");
        List<JiajiaPointsFlow> jiajiaPointsFlows = iJiajiaPointsFlowService.selectJiajiaPointsFlowList(jiajiaPointsFlowDto);
        if(Optional.ofNullable(jiajiaPointsFlows).isPresent() && jiajiaPointsFlows.size()>0) {
            for (JiajiaPointsFlow jiajiaPointsFlow:jiajiaPointsFlows) {
                BigDecimal productPoints = jiajiaPointsFlow.getProductPoints();
                //正在解锁的积分查解锁详情
                JiajiaPointsFlowDetail jiajiaPointsFlowDetailDto=new JiajiaPointsFlowDetail();
                jiajiaPointsFlowDetailDto.setIid(jiajiaPointsFlow.getIid());
                jiajiaPointsFlowDetailDto.setJiajiaOrderId(jiajiaPointsFlow.getJiajiaOrderId());
                jiajiaPointsFlowDetailDto.setUid(jiajiaPointsFlow.getUid());
                jiajiaPointsFlowDetailDto.setDeleted(0);
                List<JiajiaPointsFlowDetail> jiajiaPointsFlowDetails = iJiajiaPointsFlowDetailService.selectJiajiaPointsFlowDetailList(jiajiaPointsFlowDetailDto);
                //该订单解锁积分总和
                BigDecimal reduce = jiajiaPointsFlowDetails.stream().map(JiajiaPointsFlowDetail::getProductPoints).reduce(BigDecimal.ZERO, BigDecimal::add);
                //该项目每次抽取积分数
                BigDecimal multiply = productPoints.multiply(new BigDecimal(CacheUtils.get(Constants.SYS_CONFIG_CACHE,Constants.SYS_CONFIG_KEY+SysConfigConstants.SYS_POINTS_CONSUME_RATION).toString())).setScale(0,RoundingMode.DOWN);
                //还需解锁的积分数
                BigDecimal subtract = productPoints.subtract(reduce);
                //缺少积分数大于每次抽取比例 按抽取比例抽取
                if(subtract.compareTo(multiply)>0){
                    //有订单金额扣除
                    if(totalPrice.compareTo(multiply)>0){
                        JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
                        BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlowDetail);
                        jiajiaPointsFlowDetail.setProductPoints(multiply);
                        jiajiaPointsFlowDetail.setId(null);
                        jiajiaPointsFlowDetail.setRemark(jiajiaPointsFlowDetail.getRemark()+";订单号为"+jiajiaMallOrder.getId()+"消耗积分");
                        jiajiaPointsFlowDetail.setUnlockOrderId(jiajiaMallOrder.getId());
                        totalPrice=totalPrice.subtract(multiply);
                        pfdResult.add(jiajiaPointsFlowDetail);
                    }else{
                        //订单金额不够了
                        notEnough(totalPrice,jiajiaMallOrder.getId(),jiajiaPointsFlow,pfdResult);
                        //商城订单利润已被分配完 结束业务逻辑
                        return true;

                    }
                }else if(subtract.compareTo(multiply) == 0 ){
                    if(totalPrice.compareTo(multiply)>0){
                        JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
                        BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlowDetail);
                        jiajiaPointsFlowDetail.setProductPoints(multiply);
                        jiajiaPointsFlowDetail.setId(null);
                        jiajiaPointsFlowDetail.setRemark(jiajiaPointsFlowDetail.getRemark()+";订单号为"+jiajiaMallOrder.getOrderNum()+"消耗积分");
                        jiajiaPointsFlowDetail.setUnlockOrderId(jiajiaMallOrder.getId());
                        totalPrice=totalPrice.subtract(multiply);
                        jiajiaPointsFlow.setIntegralStatus("2");
                        pfResult.add(jiajiaPointsFlow);
                        pfdResult.add(jiajiaPointsFlowDetail);
                    }else{
                        //订单金额不够了
                        notEnough(totalPrice, jiajiaMallOrder.getId(),jiajiaPointsFlow, pfdResult);
                        //商城订单利润已被分配完 结束业务逻辑
                        return true;

                    }
                }else {
                    //还缺积分数小于了每次抽取比例 按还缺积分数抽取
                    //有订单金额扣除
                    if(totalPrice.compareTo(subtract)>0){
                        //该笔订单积分已解锁
                        JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
                        BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlowDetail);
                        jiajiaPointsFlowDetail.setProductPoints(subtract);
                        jiajiaPointsFlowDetail.setId(null);
                        jiajiaPointsFlowDetail.setUnlockOrderId(jiajiaMallOrder.getId());
                        jiajiaPointsFlowDetail.setRemark(jiajiaPointsFlowDetail.getRemark()+";订单号为"+jiajiaMallOrder.getOrderNum()+"消耗积分");
                        totalPrice=totalPrice.subtract(subtract);
                        jiajiaPointsFlow.setIntegralStatus("2");
                        pfResult.add(jiajiaPointsFlow);
                        pfdResult.add(jiajiaPointsFlowDetail);
                    }else{
                        //订单金额不够了
                        notEnough(totalPrice, jiajiaMallOrder.getId(),jiajiaPointsFlow, pfdResult);
                        //商城订单利润已被分配完 结束业务逻辑
                        return true;
                    }


                }

            }
            //还有利润未消费完
            if(totalPrice.compareTo(new BigDecimal("0"))>0){
                consumptionJiajiaPointsFlow(totalPrice,jiajiaMallOrder.getId(),pfdResult,pfResult);

            }


        }else {
            consumptionJiajiaPointsFlow(totalPrice,jiajiaMallOrder.getId(),pfdResult,pfResult);
        }
        return true;
    }


        public void notEnough(BigDecimal totalPrice,Long orderId,JiajiaPointsFlow jiajiaPointsFlow,List<JiajiaPointsFlowDetail> pfdResult)

    {
        JiajiaPointsFlowDetail jiajiaPointsFlowDetail = new JiajiaPointsFlowDetail();
        BeanUtils.copyProperties(jiajiaPointsFlow, jiajiaPointsFlowDetail);
        jiajiaPointsFlowDetail.setProductPoints(totalPrice);
        jiajiaPointsFlowDetail.setId(null);
        jiajiaPointsFlowDetail.setUnlockOrderId(orderId);
        jiajiaPointsFlowDetail.setRemark(jiajiaPointsFlowDetail.getRemark() + ";订单号为" + orderId + "消耗积分");
        pfdResult.add(jiajiaPointsFlowDetail);

    }


    public  void consumptionJiajiaPointsFlow(BigDecimal totalPrice,Long orderId,List<JiajiaPointsFlowDetail> pfdResult,List<JiajiaPointsFlow> pfResult){
        JiajiaPointsFlow jiajiaPointsFlowDto=new JiajiaPointsFlow();
        jiajiaPointsFlowDto.setDeleted(0);
        jiajiaPointsFlowDto.setPointsType("2");
        jiajiaPointsFlowDto.setIntegralStatus("0");
        List<JiajiaPointsFlow> newJiajiaPointsFlows = iJiajiaPointsFlowService.selectJiajiaPointsFlowList(jiajiaPointsFlowDto);
        for (JiajiaPointsFlow jiajiaPointsFlow:newJiajiaPointsFlows) {
            BigDecimal productPoints = jiajiaPointsFlow.getProductPoints();
            //该项目每次抽取积分数
            BigDecimal multiply = productPoints.multiply(new BigDecimal(CacheUtils.get(Constants.SYS_CONFIG_CACHE,Constants.SYS_CONFIG_KEY+SysConfigConstants.SYS_POINTS_CONSUME_RATION).toString())).setScale(0,RoundingMode.DOWN);

            if(totalPrice.compareTo(multiply)>0){
                JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
                BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlowDetail);
                jiajiaPointsFlowDetail.setProductPoints(multiply);
                jiajiaPointsFlowDetail.setId(null);
                jiajiaPointsFlowDetail.setRemark(jiajiaPointsFlowDetail.getRemark()+";订单号为"+orderId+"消耗积分");
                jiajiaPointsFlowDetail.setUnlockOrderId(orderId);
                totalPrice=totalPrice.subtract(multiply);
                jiajiaPointsFlow.setIntegralStatus("1");
                pfResult.add(jiajiaPointsFlow);
                pfdResult.add(jiajiaPointsFlowDetail);
            }else{
                JiajiaPointsFlowDetail jiajiaPointsFlowDetail=new JiajiaPointsFlowDetail();
                BeanUtils.copyProperties(jiajiaPointsFlow,jiajiaPointsFlowDetail);
                jiajiaPointsFlowDetail.setProductPoints(totalPrice);
                jiajiaPointsFlowDetail.setId(null);
                jiajiaPointsFlowDetail.setRemark(jiajiaPointsFlowDetail.getRemark()+";订单号为"+orderId+"消耗积分");
                jiajiaPointsFlowDetail.setUnlockOrderId(orderId);
                jiajiaPointsFlow.setIntegralStatus("1");
                pfResult.add(jiajiaPointsFlow);
                pfdResult.add(jiajiaPointsFlowDetail);
                break;
            }

        }

    }


}
